package com.lebang.controller.api.rouseday;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.component.RedisClient;
import com.lebang.domain.RouseCountConfig;
import com.lebang.domain.RouseCountMemberRecord;
import com.lebang.domain.RouseDayConfig;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.ResultVo;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.RewardTypeUscan;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TradeCategory;
import com.lebang.service.MemberNewTaskService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.PointService;
import com.lebang.service.RouseMoneyFilterConfigService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.buss.MemberTradeService;
import com.lebang.service.buss.WalletService;
import com.lebang.service.rouseday.RouseCountConfigService;
import com.lebang.service.rouseday.RouseDayConfigService;
import com.lebang.service.sys.AppLookCategoryService;
import com.lebang.service.sys.MemberCashWithdrawalService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

import static com.lebang.service.buss.MemberTradeService.CATEGORY_KEY;

/**
 * @Author: hwq
 * @Date: 2020/6/11 16:31
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/rouseday")
public class RouseApi {
    @Autowired
    private RouseCountConfigService rouseCountConfigService;
    @Autowired
    private RouseDayConfigService rouseDayConfigService;
    @Autowired
    private PointService pointService;
    @Autowired
    private MemberTradeService memberTradeService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private WalletService walletService;
    @Autowired
    private MemberCashWithdrawalService memberCashWithdrawalService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private MemberNewTaskService memberNewTaskService;
    @Autowired
    private MemberTradeService tradeService;

    @Autowired
    private AppLookCategoryService appLookCategoryService;

    @Autowired
    private RouseMoneyFilterConfigService rouseMoneyFilterConfigService;

    /**
     * 进度条
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @PostMapping("/countinfo")
    public JsonData info(HttpServletRequest request) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        RequestHeaders headers = new RequestHeaders(request);
        Integer all = walletService.cash(headers.getUserid(), headers.getAppid(), TradeCategory.Income.name(), RewardType.Cash.name(), null, null);
        if(rouseMoneyFilterConfigService.check(all,headers.getAppStore())){
            return Callback.fail("fail", "进度条不可见");
        }
        List<RouseCountConfig> list = rouseCountConfigService.selectConfigList();
        list.forEach(s -> {
            RouseCountMemberRecord record = rouseCountConfigService.checkConfigByMemberId(headers.getUserid(), s.getId());
            if (record == null) {
                s.setStatus(-1);
            } else {
                s.setRecord(record);
                s.setStatus(record.getStatus());
                s.setRecordId(record.getId());
            }
            if (s.getCount() > atomicInteger.get()) {
                atomicInteger.set(s.getCount());
            }
        });
        JSONObject jsonObject = new JSONObject();
        int count = rouseDayConfigService.getCount(headers);
        if (atomicInteger.get() != 0 && count >= atomicInteger.get()) {
            memberNewTaskService.addRecord(8999, headers.getUserid());
        }
        jsonObject.put("info", list);
        jsonObject.put("count", count);
        return Callback.success("success", "查询成功", jsonObject);
    }

    /**
     * 每日任务完成情况
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @PostMapping("/recordinfo")
    public JsonData info1(HttpServletRequest request) {
        RequestHeaders headers = new RequestHeaders(request);
        List<RouseDayConfig> list = rouseDayConfigService.selectConfigList(headers);
        list = review(list, headers);
        list.forEach(s -> {
            int i = rouseDayConfigService.checkConfigByMemberId(headers.getUserid(), s.getId());
            s.setStatus(i);
            s.setTotal(Optional.ofNullable(redisClient.hget(CATEGORY_KEY + s.getCategory() + ":" +
                    LocalDate.now().format(DateTimeFormatter.ISO_DATE), headers.getUserid()))
                    .map(Integer::parseInt).orElse(0));
        });
        return Callback.success("success", "查询成功", list);
    }

    /**
     * 每日任务待完成
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @PostMapping("/wait")
    public JsonData wait(HttpServletRequest request) {
        int k = 0;
        RequestHeaders headers = new RequestHeaders(request);
        List<RouseDayConfig> list = rouseDayConfigService.selectConfigList(headers);
        for (RouseDayConfig s : list) {
            int i = rouseDayConfigService.checkConfigByMemberId(headers.getUserid(), s.getId());
            if (i == 0) {
                return Callback.success("200", "查询成功", s);
            }
        }
        return Callback.fail("200", "查询成功", list);
    }

    @Require
    @Sessionid
    @PostMapping("/push")
    @Transactional(rollbackFor = Exception.class)
    @MemberLock
    public JsonData push(HttpServletRequest request, Integer recordId, Integer type) {
        RouseCountMemberRecord record = rouseCountConfigService.selectByRecordId(recordId);
        RequestHeaders headers = new RequestHeaders(request);
        try {
            if (record == null) {
                return Callback.fail("2001", "任务不存在");
            }
            if (!record.getMemberId().equals(headers.getUserid())) {
                return Callback.fail("2002", "任务不存在");
            }
            if (!record.getStatus().equals(0)) {
                return Callback.fail("2003", "任务不存在");
            }
            if (!record.getCreateDate().equals(LocalDate.now())) {
                return Callback.fail("2003", "任务不存在");
            }
            if (record.getRewardType().equals(RewardTypeUscan.Point.getIndex())) {
                pointService.addPoint(headers.getUserid(), record.getRewardWorth(), TaskCategory.ROUSE_DAY, headers, record.getMemo());
            } else if (record.getRewardType().equals(RewardTypeUscan.Cash.getIndex())) {
                memberTradeService.addMoney(headers.getUserid(), record.getRewardWorth(),
                        "每日赚点", "恭喜完成每日赚点任务", "", headers, "", new MoneyCategory(Whether.YES, TaskCategory.ROUSE_DAY));
            } else if (record.getRewardType().equals(2)) {
                if (type > 2 || type <= 0) {
                    return Callback.fail("200", "非法参数");
                }
                LbbMember member = memberService.getMemberByMemberId(headers.getUserid());
                  if (TextUtil.isEmpty(member.getWeixinName()) && type == 2) {
                    return Callback.fail("200", "申请失败,用户未实名,请让用户在个人资料填上真实姓名");
                }
                if (member.getWxStatus().equals(0) && type == 2) {
                    return Callback.fail("200", "转账失败,用户微信未绑定!!");
                }
                if (TextUtil.isEmpty(member.getAlipay(), member.getAlipayName()) && type == 1) {
                    return Callback.fail("200", "提现失败！填完支付宝账号记得点击右边【确定】按钮哦");
                }
                int amount = record.getRewardWorth();
                if (memberCashWithdrawalService.allow(headers.getUserid())) {
                    return Callback.fail("waitting", "您还有一笔提现申请未处理，请等待!");
                }
                long money = memberWalletService.getMoneyByMemberId(headers.getUserid());
                Integer amounts = walletService.getAllows(headers.getUserid(), headers.getAppid());
                if (amount > amounts || amount > money) {
                    return Callback.fail("invalid", "您的可提现金额不足!");
                }
                ResultVo vo = memberCashWithdrawalService.creatFastWishCash(member, type, amount, headers, record.getTradeNo());
                if (!vo.isSuccess()) {
                    return Callback.fail("2011", vo.getMsg(), null);
                } else {
                    //redis加钱进去
                   // tradeService.addInCashRedis(record.getMemberId(), record.getRewardWorth());
                    //mysql持久化
                    memberWalletService.outLayMoney(record.getMemberId(), record.getRewardWorth());
                }
            } else {
                return Callback.fail("202", "请求过于频繁", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Callback.fail("fail", "提现申请失败");
        }
        record.setStatus(1);
        rouseCountConfigService.updateRecord(record);
        return Callback.success("200", "领取成功");
    }


    @Require
    @Sessionid
    @PostMapping("/cash")
    public JsonData cash(HttpServletRequest request) {
        RequestHeaders headers = new RequestHeaders(request);
        List<RouseCountMemberRecord> records = rouseCountConfigService.selectWaitCashList(headers.getUserid());
        return Callback.success("success", "查询成功", records);
    }

    public List<RouseDayConfig> review(List<RouseDayConfig> list, RequestHeaders headers) {
        Integer all = walletService.cash(headers.getUserid(), headers.getAppid(), TradeCategory.Income.name(), RewardType.Cash.name(), null, null);
        list=appLookCategoryService.reviewRouse(list,headers,all);
        return list;
    }
}